import React from 'react'
import styles from './index.module.scss'
import Navbar from '@c/Navbar'
import Input from '@c/Input'
import { useFormik } from 'formik'
import { useState } from 'react'
import { useDispatch } from 'react-redux'
import { Toast } from 'antd-mobile'
import { sendValidationCode , login } from '@/store/actions/login'
import { useNavigate, useLocation } from 'react-router-dom'
export default function Login () {
  const [time,setTime] = useState(0)
  const navigator = useNavigate()
  const location = useLocation()
  const dispatch = useDispatch()
  const form = useFormik({
    initialValues: {
      mobile: '13900001111',
      code: '246810',
    },
    // 提交表单
    onSubmit: async values => {
      try {
        await dispatch(login(values))
        Toast.show('登陆成功')
        const { state } = location
        if (!state) {
          navigator('/')
        } else {
          // back 上一页
        }
        
      } catch (e) {
        if (e.response) {
          Toast.show(e.response.data.message)
        } else {
          console.log(e);
          Toast.show('服务器繁忙，请稍后再试')
        }
        
      }
      
    },
    // 表单验证
    validate(values) {
      const errors = {}
      if (values.mobile) {
        
        if(!/^1[3-9]\d{9}$/.test(values.mobile)) {
          errors.mobile = "请输入正确的手机格式"
        }
      }
      if (!values.code) {
        errors.code = '验证码不能为空'
      }
      return errors
    }
  })
  // 发送验证码
  const onSendSms = async () => {
    const mobile = form.values.mobile
    if (!/^1[3-9]\d{9}$/.test(mobile)) {
      form.setTouched({
        mobile: true,
      })
      return
    }
    try {
      const action = sendValidationCode(mobile)
      await dispatch(action)
      Toast.show('获取验证码成功')
      setTime(60)
      let timeId = setInterval(() => {
        setTime( (time) => {
          if (time === 1) {
            clearInterval(timeId)
          }
          return time - 1
        })
      }, 1000)
    } catch (error) {
      if(error.response) {
        Toast.show(error.response.data.message)
      }
    }
    
  }
  
  const { errors , values, touched , handleChange , handleSubmit } = form
    return (
      <div className={styles.root}>
        <Navbar />
        <div className="content">
        <h3>短信登录</h3>
        <form onSubmit={handleSubmit}>
          <div className="input-item">
            <div className="input-box">
              <Input
                name="mobile"
                value={values.mobile}
                placeholder="请输入您的手机号"
                onChange={handleChange}
                onBlur={handleChange}
              ></Input>
            </div>
            {touched.mobile && errors.mobile ? (
              <div className="validate">{errors.mobile}</div>
            ) : null}
          </div>
          <div className="input-item">
            <div className="input-box">
            <Input
              name="code"
              placeholder="请输入验证码"
              value={values.code}
              maxLength={6}
              onChange={handleChange}
              extra={time === 0 ? '发送验证码' : time + 's后发送'}
              onExtraClick={onSendSms}
            ></Input>
            </div>
            {errors.code ? (
              <div className="validate">验证码验证错误</div>
            ) : null}
          </div>
          {/* 登录按钮 */}
          <button type="submit" className="login-btn">
            登录
          </button>
        </form>
      </div>
      </div>
    )
  }